# -*- coding: utf-8 -*-
# @Time    : 2021/4/27 17:33
# @Author  : huangwei
# @File    : system_method.py
# @Software: PyCharm
import re
import cv2
import numpy as np


def sorted_boxes(dt_boxes):
    """
    Sort text boxes in order from top to bottom, left to right
    args:
        dt_boxes(array):detected text boxes with shape [4, 2]
    return:
        sorted boxes(array) with shape [4, 2]
    """
    num_boxes = dt_boxes.shape[0]
    sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
    _boxes = list(sorted_boxes)

    for i in range(num_boxes - 1):
        if abs(_boxes[i + 1][0][1] - _boxes[i][0][1]) < 10 and \
                (_boxes[i + 1][0][0] < _boxes[i][0][0]):
            tmp = _boxes[i]
            _boxes[i] = _boxes[i + 1]
            _boxes[i + 1] = tmp
    return _boxes


def get_rotate_crop_image(img, points):
    '''
    img_height, img_width = img.shape[0:2]
    left = int(np.min(points[:, 0]))
    right = int(np.max(points[:, 0]))
    top = int(np.min(points[:, 1]))
    bottom = int(np.max(points[:, 1]))
    img_crop = img[top:bottom, left:right, :].copy()
    points[:, 0] = points[:, 0] - left
    points[:, 1] = points[:, 1] - top
    '''
    img_crop_width = int(
        max(
            np.linalg.norm(points[0] - points[1]),
            np.linalg.norm(points[2] - points[3])))
    img_crop_height = int(
        max(
            np.linalg.norm(points[0] - points[3]),
            np.linalg.norm(points[1] - points[2])))
    pts_std = np.float32([[0, 0], [img_crop_width, 0],
                          [img_crop_width, img_crop_height],
                          [0, img_crop_height]])
    M = cv2.getPerspectiveTransform(points, pts_std)
    dst_img = cv2.warpPerspective(
        img,
        M, (img_crop_width, img_crop_height),
        borderMode=cv2.BORDER_REPLICATE,
        flags=cv2.INTER_CUBIC)
    dst_img_height, dst_img_width = dst_img.shape[0:2]
    if dst_img_height * 1.0 / dst_img_width >= 1.5:
        dst_img = np.rot90(dst_img)
    return dst_img


def normal_size(img):
    height, width = img.shape[0:2]
    if height > 2000 or width > 2000:
        if height > width:
            new_height = 2000
            new_width = int(new_height / height * width)
        else:
            new_width = 2000
            new_height = int(new_width / width * height)
        img = cv2.resize(img, (new_width, new_height))
    return img


def get_angle(boxes):
    angle_list = []
    for box in boxes:
        rect = cv2.minAreaRect(box)
        w, h = rect[1]
        angle = rect[2]

        if h > w:
            angle = abs(90 - angle)
        angle_list.append(angle)

    sort_list = sorted(angle_list)
    length = len(sort_list)
    mid_angle = sort_list[int(length / 2)]

    return mid_angle


def need_to_flip(result, shape):
    # 找到两个站的位置
    box_list = []
    for t in result:
        text = t['rec'][0]
        res = re.findall('[一-龥]+站', text)

        if len(res) != 0:
            box = t['box']
            box_list.append(box)

    # 如果均在上半区域，则无需旋转，否则需要旋转
    if len(box_list) >= 2:
        # 找到两个属于上半区域的则
        max_height = shape[1] / 2
        count = 0
        for box in box_list:
            rect = cv2.minAreaRect(box)
            cx, cy = rect[0]
            if cy < max_height:
                count += 1
            if count == 2:
                return False
    else:
        return True


def get_infomations(result, shape):
    # 先找两个站，如果没有的话则不返回
    all_info = {}
    for t in result:
        text = t['rec'][0]

        # station
        res = re.findall('[一-龥]+站', text)
        if len(res) != 0:
            box = t['box']
            rect = cv2.minAreaRect(box)
            cx, cy = rect[0]
            if cy < shape[1] / 2:
                if cx < shape[0] / 2:
                    # 为起始站
                    all_info['出发'] = res[0]
                else:
                    all_info['到达'] = res[0]

        # time
        time_res = re.findall('[0-9]{1,4}年[0-9]{1,2}月[0-9]{1,2}日', text)
        if len(time_res) > 0:
            # 日期
            time1 = time_res[0].replace('年', '-').replace('月', '-').replace('日', '')
            all_info['日期'] = time1
            # 时间
            time2_res = re.findall('[0-9]{1,2}:[0-9]{1,2}', text)
            if len(time2_res) > 0:
                time2 = time2_res[0]
                all_info['时间'] = time2

        # 姓名
        name_res = re.findall("\d*\*\d*([一-龥]{1,4})", text)
        if len(name_res) > 0:
            all_info['姓名'] = name_res[0]

        # 价格
        price_res = re.findall('￥[0-9]{1,4}.[0-9]{1,2}元', text)
        price_res += re.findall('[0-9]{1,4}.[0-9]{1,2}元', text)
        price_res += re.findall('[0-9]{1,6}元', text)
        price_res += re.findall('￥[0-9]{1,4}.[0-9]{1,2}', text)
        if len(price_res) > 0:
            all_info['车票价格'] = price_res[0].replace('￥', '').replace('元', '')

        # 座次
        seat_res = re.findall('[一-龥]{1,4}座', text)
        if len(seat_res) > 0:
            all_info['座次'] = seat_res[0]

    return all_info
